package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.util.DateUtil;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.IReturnVisitService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 预约回访信息
 *
 * @author
 * @Date
 */
@Controller
@RequestMapping("/reservationRevisit")
public class ReservationsVisitController extends BaseController {

    @Autowired
    IReturnVisitService service;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    IConsultantService consultantService;

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    IReservationsService reservationsService;

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list1")
    @ResponseBody
    public Object RecordInfoList(SearchReturnVisitInfo info, HttpServletRequest request) {
        Page<ReturnVisitInfo> page = new PageFactory<ReturnVisitInfo>().defaultPage();
        try {
            List<ReturnVisitInfo> list = new ArrayList<ReturnVisitInfo>();
            list = service.selectPageListByQuery(page, info);
            if (list.size() == 0) {
                page.setCurrent(1);
                list = service.selectPageListByQuery(page, info);
            }
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 统计查询 预约回访 人数
     */
    @RequestMapping(value = "/totalNum", method = RequestMethod.POST)
    @ResponseBody
    public List<ReservationsInfo> totalNum(String param1, String param2, String param3, String param4, String param5, String param12,
                                           String param6, String param7, String param8, String param9, String param10, String param11,
                                           String param13, String param14) throws Exception {
        //1.获取当前日期，格式为yyyy-MM-dd hh:mm:ss
        String currentDate = DateUtil.getTime(new Date()).substring(0, 10);//取今天的年月日

        //获取昨天日期字符串 格式为yyyy-MM-dd hh:mm:ss
        String lastDate = DateUtil.getAfterDayDate("-1").substring(0, 10);//取昨日 的年月日

        //获取当月的字符串
        String currerntMonth = currentDate.substring(0, 7);//yyyy-mm

        //获取上月日期
        String lastMonth = DateUtil.getAfterDayMonth("-1").substring(0, 7);//取上月的年月

        String reservationsInfo = "";
        String listHuifangTime = "left(substring_index(t.huifang,',<b>',LENGTH(huifang) - LENGTH(huifang)-1),16)";

        if (StringUtils.isNotBlank(param1)) {
            reservationsInfo += " and follower in (select t1.account from user t1 where t1.roleid='"+param1+"') ";
        }
        if (StringUtils.isNotEmpty(param2) && !"请选择".equals(param2)) {
            String outpatientName = "";
            String outpatientName2[] = param2.split(",");
            if (outpatientName2.length == 1) {
                outpatientName = outpatientName2[0];
            } else {
                for (int i = 0; i < outpatientName2.length; i++) {
                    if (i == (outpatientName2.length - 1)) {
                        outpatientName += "'" + outpatientName2[i];
                    } else if (i == 0) {
                        outpatientName += outpatientName2[i] + "'" + ",";
                    } else {
                        outpatientName += "'" + outpatientName2[i] + "'" + ",";
                    }
                }
            }
            reservationsInfo += " and t.outpatient_name in ( '" + outpatientName + "') ";
        }
        if (StringUtil.isNotEmpty(param11) && !"请选择".equals(param11)) {
            String area = "";
            String area2[] = param11.split(",");
            if (area2.length == 1) {
                area = area2[0];
            } else {
                for (int i = 0; i < area2.length; i++) {
                    if (i == (area2.length - 1)) {
                        area += "'" + area2[i];
                    } else if (i == 0) {
                        area += area2[i] + "'" + ",";
                    } else {
                        area += "'" + area2[i] + "'" + ",";
                    }
                }
            }
            reservationsInfo += " and t.outpatient_name in (select a.simplename from dept a where a.area_abbreviation in ('" + area + "')) ";
        }
        if (StringUtils.isNotBlank(param3)) {
            reservationsInfo += " and t.huifang like '%" + param3 + "%'";
        }
        if (StringUtils.isNotBlank(param4)) {
            reservationsInfo += " and t.follower ='" + param4 + "'";
        }
        if (StringUtils.isNotBlank(param5)) {
            reservationsInfo += " and t.filing_Time >='" + param5 + "'";
        }
        if (StringUtils.isNotBlank(param6)) {
            reservationsInfo += " and t.filing_Time <='" + param6 + "'";
        }
        if (StringUtils.isNotBlank(param13)) {
            reservationsInfo += " and t.status ='" + param13 + "'";
        }
        if (StringUtils.isNotBlank(param14)) {
            reservationsInfo += " and t.archiving ='" + param14 + "'";
        }
        //姓名   电话   微信  预约号
        if (StringUtils.isNotBlank(param12)) {
            reservationsInfo += " and (t.customer_name like CONCAT('%" + param12 + "%') or t.customer_phone like CONCAT('%" + param12 + "%') " +
                    " or t.customer_phone2 like CONCAT('%" + param12 + "%') " +
                    " or t.wechat_number like CONCAT('%" + param12 + "%') or t.reservations_num like CONCAT('%" + param12 + "%') " +
                    " or t.identification_number like CONCAT('%" + param12 + "%') or t.key_word like CONCAT('%" + param12 + "%') " +
                    " or t.szm like CONCAT('%" + param12 + "%')) ";
        }
        //查询今日回访
        String sql = "select count(*) as countNum from (select id from reservations_infosc t" +
                " where " + listHuifangTime + " like '" + currentDate + "%' " + reservationsInfo + " group by huifang) b" +
                //查询昨日回访
                " union all select count(*) as countNum from (select id  from reservations_infosc t" +
                " where " + listHuifangTime + " like '" + lastDate + "%' " + reservationsInfo + "  group by huifang) b" +
                //查询本周回访
                " union all select count(*) as countNum from (select id  from reservations_infosc t" +
                " where " + listHuifangTime + " >= '" + param9 + "' and " + listHuifangTime + " <= '" + param10 + "' " + reservationsInfo + " group by huifang) b" +
                //查询当月回访
                " union all select count(*) as countNum from (select id  from reservations_infosc t" +
                " where " + listHuifangTime + " like '" + currerntMonth + "%' " + reservationsInfo + "  group by huifang) b" +
                //查询上月回访
                " union all select count(*) as countNum from (select id  from reservations_infosc t" +
                " where " + listHuifangTime + " like '" + lastMonth + "%' " + reservationsInfo + "  group by huifang) b";
        //时间段查询
//                " union all select count(*) as countNum from (select id  from reservations_infosc t where  "+listHuifangTime+" >='" + param7 + "'" +
//                " and "+listHuifangTime+" <='" + param8 + "' " + reservationsInfo + " ) b "  ;
        List<ReservationsInfo> infoList = sqlMapper.selectList(sql, ReservationsInfo.class);
        return infoList;
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/reservationRevisitExport")
    public void reservationRevisitExport(@Valid SearchReturnVisitInfo searchInfo, HttpServletResponse response) {
        try {
            List<ReturnVisitInfo> list = service.reservationsExportt(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 14; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("客户姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("手机号码");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("预约门诊");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("到店状态");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("回访状态");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("二级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("三级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("回访内容");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("跟进人");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("建档人");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("建档时间");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("预约时间");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ReturnVisitInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 14; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(map.getCustomerName());
                if(Integer.parseInt(redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"PhonePrivilegesexp",0)+"")==1) {
                    row.getCell(1).setCellValue(map.getCustomerPhone());
                }else{
                    row.getCell(1).setCellValue("无");
                }
                row.getCell(2).setCellValue(map.getOutpatientName());
                row.getCell(3).setCellValue(map.getStatus());
                row.getCell(4).setCellValue(map.getStatuss());
                row.getCell(5).setCellValue(map.getOneChannel());
                row.getCell(6).setCellValue(map.getTwoChannel());
                row.getCell(7).setCellValue(map.getThrChannel());
                row.getCell(8).setCellValue(map.getSex());
                row.getCell(9).setCellValue(map.getCustomerAge());
                row.getCell(10).setCellValue(map.getHuifang());
                row.getCell(11).setCellValue(map.getFollower());
                row.getCell(12).setCellValue(map.getArchiving());
                row.getCell(13).setCellValue(map.getFilingTime());
                row.getCell(14).setCellValue(map.getAppointmentTime());
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}